// pages/edit/edit.js
const app = getApp()

Page({
  data: {
    username: '',
    nickname: '',
    email: '',
    mobile: '',
    password: '',
    confirmPassword: '',
    canEditUsername: true,
    loading: false
  },
  
  onLoad() {
    this.getUserInfo()
  },
  
  getUserInfo() {
    app.request({
      url: '/profile'
    }).then((res) => {
      const user = res.data.user || {}
      const canEditUsername = !user.username || user.username.startsWith('wx_')
      
      this.setData({
        username: user.username || '',
        nickname: user.nickname || '',
        email: user.email || '',
        mobile: user.mobile || '',
        canEditUsername: canEditUsername
      })
    }).catch((err) => {
      console.error('获取用户信息失败:', err)
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
    })
  },
  
  handleInput(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [field]: value
    })
  },
  
  goBack() {
    wx.navigateBack()
  },
  
  submitEdit() {
    if (!this.data.username.trim()) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }
    
    if (this.data.password && this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      })
      return
    }
    
    if (this.data.password && this.data.password.length < 6) {
      wx.showToast({
        title: '密码长度不能少于6位',
        icon: 'none'
      })
      return
    }
    
    this.setData({ loading: true })
    
    const submitData = {
      username: this.data.username.trim(),
      nickname: this.data.nickname.trim(),
      email: this.data.email.trim(),
      mobile: this.data.mobile.trim()
    }
    
    if (this.data.password) {
      submitData.password = this.data.password
    }
    
    if (!this.data.canEditUsername) {
      delete submitData.username
    }
    
    app.request({
      url: '/updateUserInfo',
      method: 'POST',
      data: submitData
    }).then((res) => {
      this.setData({ loading: false })
      
      wx.showToast({
        title: '修改成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      
    }).catch((err) => {
      console.error('修改用户信息失败:', err)
      this.setData({ loading: false })
      
      wx.showToast({
        title: err.message || '修改失败',
        icon: 'none'
      })
    })
  }
}) 